package com.lixin.juc.forkjoin;

import java.util.concurrent.RecursiveTask;

public class MyForkJoinTask extends RecursiveTask<Long> {

    private final Long start;
    private final Long end;

    public MyForkJoinTask(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        Long temp = 100000L;
        if (end - start <= temp) { // 如果求和范围小于或等于temp就用普通方法来求和
            Long sum = 0L;
            for (Long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else { // 如果求和范围大于temp，则将求和任务从中间拆分为两个任务
            Long middle = (end - start) / 2;
            MyForkJoinTask task1 = new MyForkJoinTask(start, middle);
            task1.fork();
            MyForkJoinTask task2 = new MyForkJoinTask(middle + 1, end);
            task2.fork();
            return task1.join() + task2.join();
        }
    }
}
